package cn.luckdou.commons.utils;

import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;



/**生成二维码的方法
 * Created by 杨 on 2017/12/29.
 */
public class QRCodeUtil {
    //二维码颜色
    private static final int BLACK = 0xFF000000;
    //二维码颜色
    private static final int WHITE = 0xFFFFFFFF;

    /**
     * 将制定内容转为二维码并以base64形式回传
     * @param text
     * @param width
     * @return
     */
    public static String QRCodeToBas64(String text,int width){
        int height=width;
        Map<EncodeHintType, Object> his = new HashMap<EncodeHintType, Object>();
        his.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);// 指定纠错等级,纠错级别（L 7%、M 15%、Q 25%、H 30%）
        his.put(EncodeHintType.CHARACTER_SET, "utf-8");//设置编码字符集
        his.put(EncodeHintType.MARGIN, 1);//设置二维码边的空度，非负数
        String result=null;
        try {
            //1、生成二维码
            BitMatrix encode = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, his);
            //2、将二维码放入缓冲流
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            //3、循环将二维码内容定入图片
            for (int i = 0; i < width; i++)
                for (int j = 0; j < height; j++)
                    image.setRGB(i, j, encode.get(i, j) ? BLACK : WHITE);
            //4.将image转为base64
            result= putImage(image);
        } catch (WriterException e) {
            e.printStackTrace();
            System.out.println("二维码生成失败");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("二维码转base64失败");
        }
        return result;
    }


    /**
     * @param text    二维码内容
     * @param width    二维码宽
     * @param height    二维码高
     * @param outPutPath    二维码生成保存路径
     * @param imageType        二维码生成格式
     */
    public static void zxingCodeCreate(String text, int width, int height, String outPutPath, String imageType) {
        Map<EncodeHintType, String> his = new HashMap<EncodeHintType, String>();
        //设置编码字符集
        his.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try {
            //1、生成二维码
            BitMatrix encode = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, his);

            //2、获取二维码宽高
            int codeWidth = encode.getWidth();
            int codeHeight = encode.getHeight();

            //3、将二维码放入缓冲流
            BufferedImage image = new BufferedImage(codeWidth, codeHeight, BufferedImage.TYPE_INT_RGB);

            for (int i = 0; i < codeWidth; i++) {
                for (int j = 0; j < codeHeight; j++) {
                    //4、循环将二维码内容定入图片
                    image.setRGB(i, j, encode.get(i, j) ? BLACK : WHITE);
                }
            }
            String s = putImage(image);
            System.out.println( "<img src= \"data:image/png;base64," + s + "\"/>");
//            File outPutImage = new File(outPutPath);
//            //如果图片不存在创建图片
//            if (!outPutImage.exists())
//                outPutImage.createNewFile();
//            //5、将二维码写入图片
//            ImageIO.write(image, imageType, outPutImage);
        } catch (WriterException e) {
            e.printStackTrace();
            System.out.println("二维码生成失败");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("生成二维码图片失败");
        }
    }

    private static String putImage(Image image)
            throws IOException {
        BufferedImage bimg = new BufferedImage(image.getWidth(null),
                image.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics g = bimg.createGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(bimg, "jpeg", outputStream);
        BASE64Encoder encoder = new BASE64Encoder();
        String base64Img = encoder.encode(outputStream.toByteArray());
        return "data:image/jpeg;base64,"+base64Img;
    }



    public static  void main(String[] args){
//        QRCodeUtil.zxingCodeCreate("http://wx.havezone.com/", 150,150, "E://icon.png","jpg");
        String base64code = QRCodeToBas64("http://weixin.qq.com/q/02guFjwrEZbR-10000w03J", 300);
        System.out.println(base64code);

    }


}
